package net.jacqeush.mini.rpc.client.processor;

import net.jacqeush.mini.rpc.client.Client;
import net.jacqeush.mini.rpc.client.annotation.RpcReference;
import net.jacqeush.mini.rpc.client.properties.RpcClientProperties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * @author Jacquesh
 * @version 1.0
 * @date 2020/10/22 8:37
 */
@Component
public class RpcBeanPostProcessor implements BeanPostProcessor {
    private Client client;
    private RpcClientProperties config ;
    public RpcBeanPostProcessor(Client client, RpcClientProperties config) {
        this.client=client;
        this.config=config;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> targetClass = bean.getClass();
        Field[] declaredFields = targetClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            RpcReference rpcReference = declaredField.getAnnotation(RpcReference.class);
            if (rpcReference != null) {
                declaredField.setAccessible(true);
                try {
                    Object o;
                    if (this.config.isAsync()){
                     o=client.invokeAsync(declaredField.getType());
                    }else{
                     o= client.invokeSync(declaredField.getType());
                    }
                    declaredField.set(bean, o);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

        }
        return bean;
    }
}
